package com.google.code.syncgear.plugin.dispatch;

import java.util.List;
import java.util.logging.Logger;

import net.bican.wordpress.Page;
import net.bican.wordpress.Wordpress;
import redstone.xmlrpc.XmlRpcFault;

import com.google.code.syncgear.plugin.AbstractDispatch;
import com.google.code.syncgear.plugin.bean.FetchResult;
import com.google.code.syncgear.util.DateTimeUtil;

public final class WordpressDispatch extends AbstractDispatch {

	private static final long serialVersionUID = -441853032601804427L;
	
	private static final Logger log = Logger.getLogger(WordpressDispatch.class.getName());
	
	private Wordpress wordpress;

	@Override
	protected boolean init(List<String> target) {
		String username = target.get(0);
		String password = target.get(1);
	    String xmlRpcUrl = target.get(2);
	    String sayHelloResponse = "";
	    try {
			wordpress = new Wordpress(username, password, xmlRpcUrl);
			sayHelloResponse = wordpress.sayHello();
		} catch (Exception e) {
			log.warning(e.getMessage());
			log.warning("===========================");
			log.warning(sayHelloResponse);
			return false;
		}
		return true;
	}

	@Override
	protected boolean auth(List<String> target) {
		return true;
	}

	@Override
	protected boolean process(List<String> target, FetchResult fetchResult) {
		boolean isSuccess = true;

		try {
			Page recentPost = new Page();
			recentPost.setTitle(fetchResult.getTitle());
			String description = fetchResult.getDescription();
			if(description == null)
				description = "";
			if(fetchResult.getImage() != null) {
				if(description.trim().length() == 0)
					description = "<p><img src='" + fetchResult.getImage() + "' border='0'></p>";
				else
					description += "</br><p><img src='" + fetchResult.getImage() + "' border='0'></p>";
			}
			if(fetchResult.getTags() != null)
				if(fetchResult.getTags().replace(",", "").trim().length() > 0) {
					recentPost.setMt_keywords(fetchResult.getTags());
				}			
		    recentPost.setDescription(description);
		    recentPost.setDateCreated(DateTimeUtil.getNow());
		    recentPost.setDate_created_gmt(DateTimeUtil.getNow());
		    wordpress.newPost(recentPost, true);
		} catch (XmlRpcFault e) {
			log.warning(e.getMessage());
			isSuccess = false;
		}

		return isSuccess;
	}

}
